package com.sh.personnel.controller.sys;

import com.github.pagehelper.PageInfo;
import com.sh.personnel.domain.ITbRole;
import com.sh.personnel.service.IRoleService;
import com.sh.personnel.util.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 角色控制
 * @author 林思浩
 * @date 2020/03/12 17:50
 */
@RestController
@RequestMapping("/role")
public class IRoleController {

    @Autowired
    IRoleService roleService;

    //获取所有角色ID和名称选项
    @GetMapping("/select")
    public Result getSelectRoleIdAndName() {
        List<HashMap<String, String>> roleList = roleService.getRoleIdAndName();
        return Result.success().setData("role_select", roleList);
    }

    //分页获取角色列表
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:role:view')")
    public Result getRoleAllList(@RequestParam("page") Integer page,
                                 @RequestParam(required = false, value = "key") String key) {
        PageInfo<ITbRole> roleList = roleService.getRoleList(page, key);
        return Result.success().setData("role_list", roleList);
    }

    //添加新角色
    @PostMapping()
    @PreAuthorize("hasAuthority('sys:role:insert')")
    public Result addNewRole(@RequestBody ITbRole role) {
        boolean bool = roleService.addRoleNew(role);
        return bool ? Result.success() : Result.fail();
    }

    //更新角色信息
    @PutMapping()
    @PreAuthorize("hasAuthority('sys:role:update')")
    public Result alterRole(@RequestBody ITbRole role) {
        boolean bool = roleService.updateRoleById(role);
        return bool ?  Result.success() : Result.fail();
    }

    //获取角色信息
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:role:info')")
    public Result getRoleById(@PathVariable String id) {
        ITbRole role = roleService.getRoleById(id);
        return Result.success().setData("role", role);
    }

    //删除角色
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    public Result deleteRole(@PathVariable String id) {
        boolean bool = roleService.deleteRoleById(id);
        return bool ? Result.success() : Result.fail();
    }
}
